/**************************************************************************(C)*
 *
 *  This file is part of the GreenHills project
 *  Copyright (C) 2009  Tieto Corporation
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  Not for commmercial use. Only with Tieto permission.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *************************************************************************(C)*/

#include "client.h"

#include "../io/connection.h"
#include "../util/binstream.h"
#include "../util/memstreambuf.h"
#include "../event/event.h"

using namespace greenhills::server;
using namespace greenhills::event;
using namespace greenhills::util;
using namespace greenhills::io;

CClient::CClient(const std::string &pUserName)
    :mClientId(getUniqueClientId())
{
    mUserName = pUserName;
    mEventConnection = 0;
    mActionConnection = 0;
}

void CClient::assignActionConnection(CConnection *pConnection)
{
    mActionConnection = pConnection;
}

void CClient::assignEventConnection(CConnection *pConnection)
{
    mEventConnection = pConnection;
}

greenhills::core::CClientId CClient::getUniqueClientId()
{
    static greenhills::core::CClientId clientId = 0;
    return ++clientId;
}

void CClient::sendResponse(const CEvent *event)
{
    CClient::send(mActionConnection, event);
}

void CClient::sendEvent(const CEvent *event)
{
    CClient::send(mEventConnection, event);
}

void CClient::send(CConnection *pConnection,
        const CEvent *event)
{
    memstreambuf buffer;
    obinstream os(&buffer);
    CEvent::serialize(event, os);
    pConnection->sendMessage( buffer.data(), buffer.length());
}

